import React, { Component } from 'react'
import styles from './index.module.scss'

/**
 * 吸顶效果组件
 */

export default class Sticky extends Component {

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll)
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  }

  handleScroll = () => {
    const { top } = this.placeholder.getBoundingClientRect();
    const { height } = this.content.getBoundingClientRect();
    // console.log(top);
    // 获取元素的top值，如果小于0说明已经不在页面中
    if (top < 0) {
      this.content.classList.add(styles.fixed);
      this.placeholder.style.height = height + 'px';
    } else {
      this.content.classList.remove(styles.fixed);
      this.placeholder.style.height = 0;
    }
  }

  render() {
    return (
      <div>
        <div ref={c => this.placeholder = c}/>
        <div ref={c => this.content = c}>{this.props.children}</div>
      </div>
    )
  } 
}
